package com.working.libcommon.exts

import android.app.Activity
import android.content.Intent
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.ColorInt
import androidx.core.app.ActivityOptionsCompat
import com.working.libcommon.util.getType

inline fun <reified T> Activity.setResultData(data: T) {
    val type = getType<T>()
    setResult(Activity.RESULT_OK, Intent().putExtra(type.toString(), data?.toJson(type)))
    finish()
}

inline fun <reified T> ComponentActivity.startForResult(
    clazz: Class<out Activity>,
    options: ActivityOptionsCompat? = null,
    noinline extra: (Intent.() -> Unit)? = null,
    crossinline onResult: (T) -> Unit
) {
    val type = getType<T>()
    val arc = ActivityResultContracts.StartActivityForResult()
    val launcher = registerForActivityResult(arc) { activityResult ->
        if (activityResult.resultCode == Activity.RESULT_OK) {
            val data = activityResult.data?.getStringExtra(type.toString())
            data?.parseJson<T>(getType<T>())?.let(onResult)
        }
    }

    launcher.launch(
        Intent(this, clazz).apply {
            extra?.invoke(this)
        }
        , options
    )
}

fun Activity.statusBarColor(@ColorInt color: Int) {
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
    window.statusBarColor = color
}